package main

import (
	"api/config"
	"api/libs/register"
	"flag"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/task"
	"net/http"
	"os"
	"path"
	"regexp"
	"strings"
	"time"
)

var port, root string
var debug bool

func main() {
	flag.StringVar(&port, "port", "80", "启动端口")
	flag.StringVar(&root, "root", "./", "启动目录")
	flag.BoolVar(&debug, "debug", false, "调试")
	flag.Parse()
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		//检验是否是文件
		url := request.RequestURI
		logOut(fmt.Sprintf("url=%s", url))
		filePath := fmt.Sprintf("%s%s", root, url)
		fileInfo, e := os.Stat(fmt.Sprintf("%s%s", root, url))

		if os.IsNotExist(e) || fileInfo.IsDir() {

			//检查是否是相对路径的文件
			reg := regexp.MustCompile(`(?P<a>.+?)(?P<any>/(.+?)__)(?P<b>[a-z]+)/(?P<c>.+)(?P<d>\.(ttf|woff|woff2))`)
			filePath = reg.ReplaceAllString(url, "${a}_${b}/fonts/${c}${d}")

			logOut(fmt.Sprintf("filePath1=%s", filePath))
			fileInfo, e = os.Stat(fmt.Sprintf("%s%s", root, filePath))
			if os.IsNotExist(e) {
				logOut(fmt.Sprintf("is not file=%s", filePath))
				//不是文件,读取首页
				tmp := strings.Split(url[1:], "/")
				if len(tmp) == 0 {
					filePath = "./index.html"
				} else {
					filePath = fmt.Sprintf("%s/index.html", root)
				}
			} else {
				filePath = fmt.Sprintf("%s%s", root, filePath)
				logOut(fmt.Sprintf("isfile=%s", filePath))
			}

		} else {
			if !os.IsNotExist(e) {
				writer.Header().Set("Cache-Control", "public, max-age=31536000")
				if path.Ext(fileInfo.Name()) == ".css" {
					//content-type: text/css
					writer.Header().Set("Content-Type", "text/css")
				}
			}
		}
		logOut(fmt.Sprintf("filePath——2=%s", filePath))
		content, e := os.ReadFile(filePath)
		if e != nil {
			println(e.Error())
		}
		_, e = writer.Write(content)
		if e != nil {
			println(e.Error())
		}
	})
	http.HandleFunc("/_heart_beat", func(writer http.ResponseWriter, request *http.Request) {
		_, e := writer.Write([]byte(fmt.Sprintf("%d", time.Now().Unix())))
		ez.PrintError(e)
	})
	//注册到服务中心
	register.RegService()
	task.NewTask("service_heart_beat", func() {
		register.HeartBeat()
	}).SetEvery(config.GetService().Register.HearBeatInterval)
	task.Start()
	e := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
	if e != nil {
		println("WebServerStartError", e.Error())
	}
	return
}

func logOut(data string) {
	if debug {
		println(data)
	}
}
